import {defineStore} from 'pinia'
import router from '@/router'
import {getToken, setToken, removeToken} from '@/utils/token'
import api from "@/api"
import http from "@/utils/http"

const useUserStore = defineStore('user', {
    state: () => ({
        token: '',
        userInfo:{},
        permissions: [],
    }),
    actions: {
        setToken(token) {
            this.token = token
        },

        logout() {
            return new Promise(async (resolve, reject) => {
                const {data: res} = await http.post(api.logout, {})
                if (res.code == 200) {
                    removeToken()
                    this.token = ''
                    this.permissions = []
                    router.push({path: '/login'})
                    resolve()
                }
            })

        }
    },
    getters: {
        getToken: (state) => {
            return state.token
        }
    },
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'user',
                storage: localStorage,
                path: [] //可以选择保存的字段  其余的不保存
            }
        ]
    }
})

export default useUserStore
